package com.example.xmlfactory.parse.sax;

import com.example.xmlfactory.parse.ClassMsg;
import com.example.xmlfactory.parse.Serializer;
import com.example.xmlfactory.parse.Var;

import org.xml.sax.helpers.AttributesImpl;

import java.io.StringWriter;
import java.util.Map;
import java.util.Set;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

/**
 * Created by huangbei on 2017/9/11.
 */

public class SaxSerializer implements Serializer{

    private ClassMsg classMsg;

    @Override
    public String serialize(Object obj) {
        try {

            classMsg = new ClassMsg(obj);

            SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();//取得SAXTransformerFactory实例
            TransformerHandler handler = factory.newTransformerHandler();           //从factory获取TransformerHandler实例
            Transformer transformer = handler.getTransformer();                     //从handler获取Transformer实例
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");            // 设置输出采用的编码方式
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");                // 是否自动添加额外的空白
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");   // 是否忽略XML声明

            StringWriter writer = new StringWriter();
            Result result = new StreamResult(writer);
            handler.setResult(result);

            String uri = "";    //代表命名空间的URI 当URI无值时 须置为空字符串
            String localName = "";  //命名空间的本地名称(不包含前缀) 当没有进行命名空间处理时 须置为空字符串

            handler.startDocument();

            handler.startElement(uri,localName,classMsg.getClassName(),null);

            AttributesImpl attrs = new AttributesImpl();//负责存放元素信息

            Map<String,Var> properties = classMsg.getProperties();
            Set<String> keys = properties.keySet();
            for(String key : keys){
                handler.startElement(uri,localName,key,null);

                Var var = properties.get(key);
                String str = var.getValue().toString();
                handler.characters(str.toCharArray(),0,str.length());

                handler.endElement(uri,localName,key);
            }

            handler.endElement(uri,localName,classMsg.getClassName());

             return writer.toString();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
